package com.dengxiujun.simpletomcat.handler;

import com.dengxiujun.simpletomcat.dispatcher.ServletDispatcher;
import com.dengxiujun.simpletomcat.request.HttpRequest;
import com.dengxiujun.simpletomcat.response.HttpResponse;

import java.io.IOException;
import java.nio.channels.SocketChannel;

/**
 * <p></p>
 *
 * @author dengxiujun
 * @date 2021-04-26
 **/
public class NIOConnectionHandler implements Runnable {

    private SocketChannel socketChannel;

    public NIOConnectionHandler(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    @Override
    public void run() {
        try {
            HttpResponse rep = new HttpResponse(socketChannel);
            try {
                HttpRequest req = new HttpRequest(socketChannel);
                ServletDispatcher.dispatch(req, rep);
            } catch (RuntimeException e) {
                rep.write(e.getMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socketChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public SocketChannel getSocketChannel() {
        return socketChannel;
    }

    public void setSocketChannel(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

}
